#coding=utf-8


from XMLGenerator.T_XML import T_XML

from ExcelReader.RowGenerator import BaseRowGenerator
import os.path
from pymongo import MongoClient
import xlrd
from HTGenerator.HTBaseGenerator import *



def error(msg):
    sys.stderr.write('%s\n'%msg)
    raise Exception(msg)

def _print_table_name(data):
    #打印所有的工作表名
    for table_name in data.sheet_names():
        print table_name
def _print_first_table_name(data):
    #打印第一个工作表的名字
    print '####  %s   ###'%data.sheet_names()[0]

def _print_row_value(row_value):
    #读取到的类型可能非 unicode类型 所以要判断、转换
    des = ''
    for value in row_value:
        if type(value) != unicode:
            value = str(value)
        if value == '':
            value = 'None'
        des = des + ' ' + value
    print des

def _file_name(file_path):
    file_name = os.path.basename(file_path)
    strs = file_name.split('.')
    return strs[0]


class SpecailEmployeeOperationRow(BaseRowGenerator):
    def __init__(self, row_value):
        super(SpecailEmployeeOperationRow, self).__init__(row_value)

    #提取出来后返回True，否则返回False
    def collect_useful_data(self):
        # print self.inited_row_value
        try:
            '''
            暂时先这样处理，后面会根据标题确定数据类型
            '''
            self.job = self.inited_row_value[0]
            self.operation_name = self.inited_row_value[1]
            self.operation_object = self.inited_row_value[2]

            self.clause_location = self.inited_row_value[6]
            self.special_clause_id = self.inited_row_value[7]
            self.special_clause_content = self.inited_row_value[8]

        except Exception,e:
            error('ReadDataError:%s'%('|'.join(['%s'%item for item in self.row_value])))
            self.isCollected = False
        self.isCollected = True

    def check_update_useful_value(self, content):

        if self.operation_object == '附件':
            self.operation_object_type = OPERATION_TYPE_APPENDIX
        elif self.operation_object == '一级条款':
            self.operation_object_type = OPERATION_TYPE_FIRST_LEVEL
        elif self.operation_object == '二级条款':
            self.operation_object_type = OPERATION_TYPE_SECOND_LEVEL
        elif self.operation_object == '三级条款':
            self.operation_object_type = OPERATION_TYPE_THIRD_LEVEL
        else:
            error("ERROR:%s操作对象无效" % ' '.join([str(item) for item in self.inited_row_value]))
            return False

        if self.operation_name == "增加":
            self.operation_type = OPERATION_ADD
        elif self.operation_name == "替换":
            self.operation_type = OPERATION_REPLACE
        elif self.operation_name == "删除":
            self.operation_type = OPERATION_DELETE
        else:
            error("ERROR:%s操作方式无效" % self.operation_name)
            return False

        types = [OPERATION_ADD, OPERATION_REPLACE]

        if self.operation_type in types and  self.operation_object_type != OPERATION_TYPE_APPENDIX:
            if self.special_clause_id is None:
                error("ERROR:%s无法找到条款ID" % self.job)
                return False

        self.content = content
        return True

    def __str__(self):
        return ' '.join(self.inited_row_value)


class ContractGenerator(HTBaseGenerator):
    def __init__(self, special_rows, industry_name,generate_file_type ,ht_set_type, original_contract_file, saved_dir):
        super(ContractGenerator, self).__init__(special_rows, industry_name, generate_file_type, ht_set_type, original_contract_file, saved_dir)

    def init_data(self):
        for special_row in self.special_rows:
            job_identity = "%s_%s" %(self.industry_name, special_row.job)
            job_id = md5(job_identity)
            self.jobid2_industy_job[job_id] = job_identity

    #返回保存的路径
    def generate_one_contract(self, file_name):
        #提取行业职位
        pre_job_identity = None
        current_xml_generator = None
        contract_number = 1
        job_number = 0
        for index, special_row in enumerate(self.special_rows):
            self.current_row_index = index
            job_identity = "%s_%s" %(self.industry_name, special_row.job)
            #初始化新一份劳动合同
            if pre_job_identity == None or pre_job_identity != job_identity:
                job_number += 1

                print "INFO--------%d %s ----------" % (job_number, job_identity)

                contract_number = self._save_xml(pre_job_identity, current_xml_generator,contract_number, file_name)
                current_xml_generator = XMLFileGenerator(self.original_contract_file)

            pre_job_identity = job_identity

            self._deal_per_special_row(special_row, current_xml_generator)

            if contract_number == 2:
                break
        # #保存最后一份合同
        contract_number = self._save_xml(pre_job_identity, current_xml_generator, contract_number, file_name)

        if len(self.repeat_jobs) > 0:
            print "WARNING: %s 存在重复职位" % "|".join(self.repeat_jobs)

        return self.saved_dir + "/" + file_name


'''
row_value 为行数据
row 表示行号
merged_cells_map  合并单元格的值,字典格式 key 为(row, col) value 为单元格value
'''
def update_row_value(row_value, row, merged_cells_map):

    new_data = [];

    for index, value in enumerate(row_value):
        if type(value) == unicode:
            value = str(value)
            if value == "":
                cell_loc = "(%d,%d)" % (row, index)

                if cell_loc in merged_cells_map.keys():
                    value = merged_cells_map[cell_loc]

        new_data.append(value)
    return new_data

'''
处理被合并的单元格的数据 给被合并的单元格赋予同样的值
'''

def get_merged_cells_map(table):
    merged_cells_map = {}
    for crange in table.merged_cells:
        rlo, rhi, clo, chi = crange
        # print rlo, rhi, clo, chi
        for r in range(rlo, rhi):
            for c in range(clo, chi):
                cell = table.cell(r,c)
                value = cell.value
                cell_loc = "(%d,%d)"%(r,c)
                if value == "":
                    #排除合并单元格区域的第一行
                    if r > rlo:
                        top_cell_loc = "(%d,%d)"%(r-1,c)
                        top_cell_value = merged_cells_map[top_cell_loc]
                        value = top_cell_value
                merged_cells_map[cell_loc] = value
    return merged_cells_map

def read_industry_special_excel_file(file_path, industry_name,ht_set_type, saved_dir, original_contract_file):
    isExist = os.path.exists(file_path)
    if not isExist:
        error('ERROR:%s该文件不存在'%file_path)
        return

    '''
    读取excel数据
    '''
    data = xlrd.open_workbook(file_path)
    # _print_first_table_name(data)
    print '########    %s     #########' % industry_name
    '''
    后期加上合法性检查
    '''
    if len(data.sheets()) < 2:
        error('ERROR::%s该文件中不包含表'%file_path)
        return

    table = data.sheets()[1]


    '''
    处理被合并的单元格的数据 给被合并的单元格赋予同样的值
    '''
    merged_cells_map = get_merged_cells_map(table)


    '''
    更新数据
    '''
    mongo_client = MongoClient(host='127.0.0.1', port=27017, document_class=dict, tz_aware=None, connect=None)
    db = mongo_client["CLAUSES"]
    col = db["special_clauses"]

    special_rows = []

    match_all_jobs_rows = []
    for row_index in range(1,table.nrows):
        row_value = table.row_values(row_index)
        row_value = update_row_value(row_value, row_index, merged_cells_map)

        special_row = SpecailEmployeeOperationRow(row_value)
        content = None
        if not special_row.isCollected:
            raise Exception('收集有用数据失败%s' % special_row)
            continue

        if special_row.special_clause_id:
            repr = col.find_one({'_id':special_row.special_clause_id})
            content = repr['content']
        if special_row.check_update_useful_value(content) == True:
            if '全部行业' == special_row.job:
                match_all_jobs_rows.append(special_row)
            else:
                special_rows.append(special_row)
        else:
            raise Exception("改行数据不合法%s" % special_row)


    mongo_client.close()

    '''
    生成该行业通用员工手册
    '''

    if len(match_all_jobs_rows) > 0:
        generator = ContractGenerator(match_all_jobs_rows, industry_name, "employee" ,ht_set_type, original_contract_file, saved_dir)
        new_origin_file_path = generator.generate_one_contract('employee.xml')
        if new_origin_file_path is None:
            error('Error:生成该行业通用员工手册失败')
        else:
            original_contract_file = new_origin_file_path



    generator = ContractGenerator(special_rows, industry_name, "employee",ht_set_type, original_contract_file, saved_dir)

    generator.generate_contract()

    generator.write_to_map_file('employee_map.txt')


if __name__ == '__main__':
    industry_file_paths = ['Contract/catering/catering.xlsx']

    industry_dir_name_maps = {
        'Contract/catering/catering.xlsx':'餐饮业'
    }

    for index, file_path in enumerate(industry_file_paths):
        # if index == 0:
        industry_name = industry_dir_name_maps[file_path]
        subDirs = file_path.split('/')

        saved_dir = '/'.join([subDirs[0], subDirs[1]])
        read_industry_special_excel_file(file_path, industry_name, "劳动合同", saved_dir, 'Contract/employee.xml')
